package com.mindskip.xzs.utility;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 限流工具包
 */
public class RateLimiter {
    // 阈值
    private static Integer QPS = 100;

    // 时间窗口（毫秒）
    private static long TIME_WINDOWS = 1000;

    // 计数器
    private static AtomicInteger REQ_COUNT = new AtomicInteger();
    //当前时间
    private static long START_TIME = System.currentTimeMillis();

    public synchronized static boolean tryAcquire() {
        if ((System.currentTimeMillis() - START_TIME) > TIME_WINDOWS) {
            REQ_COUNT.set(0);
            START_TIME = System.currentTimeMillis();
        }
        return REQ_COUNT.incrementAndGet() <= QPS;
    }
}
